/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.vdialog.view.node;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import offset.nodes.Constants;
import offset.nodes.client.model.Initializable;
import offset.nodes.client.vdialog.model.node.GetVirtualPageInstances;
import offset.nodes.client.vdialog.model.node.InstanceInfo;
import offset.nodes.client.model.ActivePanelContainer;
import offset.nodes.client.model.Server;
import offset.nodes.client.model.Validator;

/**
 *
 * @author Walter Lütgenau
 */
public class NewNodeFromVirtualPagePanel extends javax.swing.JPanel implements Validator, Initializable {

    Server server;
    HashMap<String, List<InstanceInfo>> toInstance = new HashMap<String, List<InstanceInfo>>();
    boolean initialized = false;

    /** Creates new form NewNodeFromVirtualPagePanel */
    public NewNodeFromVirtualPagePanel(Server server) {
        this.server = server;
        initComponents();
    }

    /**
     * Initialize the combo boxes
     */
    protected void init() {
        GetVirtualPageInstances.Request request = new GetVirtualPageInstances.Request();
        GetVirtualPageInstances.Response response = null;
        try {
            response = (GetVirtualPageInstances.Response) server.sendRequest(request);
            for (InstanceInfo info : response.getInstances()) {
                List infos = toInstance.get(info.getNodeTypeName());
                if (infos == null)
                    infos = new ArrayList<InstanceInfo>();

                infos.add(info);

                toInstance.put(info.getNodeTypeName(), infos);
            }

            typeCombo.removeAllItems();

            List<String> instances = new ArrayList<String>(toInstance.keySet());
            Collections.sort(instances);
            for (String type : instances) {
                typeCombo.addItem(type);
            }

            updateInstanceCombo();

            typeCombo.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    updateInstanceCombo();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void updateInstanceCombo() {
        instanceCombo.removeAllItems();
        for (InstanceInfo info : toInstance.get((String) typeCombo.getSelectedItem())) {
            instanceCombo.addItem(info.getInstancePath());
        }
    }

    @Override
    public void init(ActivePanelContainer container) {
        if (!initialized) {
            init();
            initialized = true;
        }
    }

    @Override
    public boolean isValidPane() {
        return typeCombo.getSelectedItem() != null && instanceCombo.getSelectedItem() != null && nameTextField.getText() != null && nameTextField.getText().length() > 0;
    }

    /**
     * Return the name selected by the user
     * @return
     */
    public String getVirtualPageName() {
        return nameTextField.getText();
    }

    /**
     * Return the node type of the node to be created.
     * 
     * @return
     */
    public String getNodeType() {
        return (String) typeCombo.getSelectedItem();
    }

    /**
     * Return the uuid of the instance selected by the user
     * @return
     */
    public String getInstanceUuid() {
        for (InstanceInfo info : toInstance.get((String) typeCombo.getSelectedItem())) {
            if (info.getInstancePath().equals((String) instanceCombo.getSelectedItem()))
                return info.getInstanceUuid();
        }

        return null;
    }

    /**
     * Return the requested edit operation.
     * 
     * @return
     */
    public boolean doEdit() {
        return editCheckbox.isSelected();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nameLabel = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        typeLabel = new javax.swing.JLabel();
        typeCombo = new javax.swing.JComboBox();
        instanceLabel = new javax.swing.JLabel();
        instanceCombo = new javax.swing.JComboBox();
        editCheckbox = new javax.swing.JCheckBox();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/vdialog/view/DialogBundle"); // NOI18N
        nameLabel.setText(bundle.getString("virtualNode.name")); // NOI18N

        typeLabel.setText(bundle.getString("virtualNode.type")); // NOI18N

        typeCombo.setModel(new DefaultComboBoxModel());
        typeCombo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                selectNodeTypeByKey(evt);
            }
        });

        instanceLabel.setText(bundle.getString("virtualNode.templateInstance")); // NOI18N

        instanceCombo.setModel(new DefaultComboBoxModel());

        editCheckbox.setSelected(true);
        editCheckbox.setText(bundle.getString("virtualNode.edit")); // NOI18N
        editCheckbox.setMargin(new java.awt.Insets(0, 0, 2, 2));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nameLabel)
                    .addComponent(typeLabel)
                    .addComponent(instanceLabel))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(editCheckbox)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(nameTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                        .addComponent(typeCombo, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(instanceCombo, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(161, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(53, 53, 53)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(typeLabel)
                    .addComponent(typeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(instanceCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(instanceLabel))
                .addGap(26, 26, 26)
                .addComponent(editCheckbox)
                .addContainerGap(96, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void selectNodeTypeByKey(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_selectNodeTypeByKey
        int selected = typeCombo.getSelectedIndex();
        if (selected < 0)
            selected = 0;

        int newSelected = -1;
        for (int i = selected + 1; i < typeCombo.getItemCount(); i++) {
            String[] name = ((String) typeCombo.getItemAt(i)).toLowerCase().split(Constants.NAMESPACE_DELIMITER);
            if (name[1].charAt(0) == Character.toLowerCase(evt.getKeyChar())) {
                newSelected = i;
                break;
            }
        }

        if (newSelected < 0)
            for (int i = 0; i < selected; i++) {
                String[] name = ((String) typeCombo.getItemAt(i)).toLowerCase().split(Constants.NAMESPACE_DELIMITER);
                if (name[1].charAt(0) == Character.toLowerCase(evt.getKeyChar())) {
                    newSelected = i;
                    break;
                }
            }

        if (newSelected >= 0)
            typeCombo.setSelectedIndex(newSelected);

    }//GEN-LAST:event_selectNodeTypeByKey
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox editCheckbox;
    private javax.swing.JComboBox instanceCombo;
    private javax.swing.JLabel instanceLabel;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JComboBox typeCombo;
    private javax.swing.JLabel typeLabel;
    // End of variables declaration//GEN-END:variables
}
